import com.documentum.com.*
import com.documentum.fc.common.*
import com.documentum.fc.client.*

class CabinetLister {
    def username
    def password
    def docbase
    final static def DQL = "select object_name from dm_cabinet order by object_name"
    
    CabinetLister(params) {
        username = params[0]
        password = params[1]
        docbase = params[2]
    }

    def getCabinetNames() {
        def cabinetNames = []
        def clientx = new DfClientX()
        def client
        def manager
        def session
        def loginInfo
        def results
        def query

        try {
            loginInfo = clientx.loginInfo
            loginInfo.user = username
            loginInfo.password = password

            client = clientx.localClient
            manager = client.newSessionManager()
            manager.setIdentity(docbase, loginInfo)
            session = manager.getSession(docbase)
            println "Connected to docbase $session.docbaseName OK"
            
            query = clientx.query
            query.DQL = DQL
            results = query.execute(session, IDfQuery.DF_READ_QUERY)
            if(results) {
                while(results.next()) {
                    cabinetNames << results.getString("object_name")
                }
            }
        } finally {
            if(session) {
                results?.close()
                manager?.release(session)
                println "Disconnected OK"
            }
        }
        
        cabinetNames
    }
    
    static main(args) {
        final def separator = '-'.multiply(20)
        if(args.size() == 3) {
            try {
                println separator
                def cabinetNames = new CabinetLister(args).cabinetNames
                println separator
                cabinetNames.each { println "Found cabinet = $it" }
            } catch(DfException e) {
                println "Error detected\n${e.message}"
            }
        } else {
            println "Usage: groovy CabinetLister username password docbase"
        }
    }
}